<template>
    <Popup ref="popupRef" title="权限设置" :formData="formData" @submit="handleSubmit" @cancel="handleCancel">
        <template #default="{ formData }">


            <a-scrollbar style="height:400px;overflow: auto;">
                <a-form-item label="" name="role">
                    <a-tree :data="MenuTree" :checkable="true" showLine v-model:checked-keys="checkedKeys"
                        v-model:half-checked-keys="halfCheckedKeys" v-model:expanded-keys="expandedKeys"
                        :fieldNames="{ key: 'id', title: 'name' }" :default-expand-all="true" />
                </a-form-item>
            </a-scrollbar>

        </template>
    </Popup>
</template>

<script setup lang="ts">
import Popup from '@/components/Popup/index.vue'
import { getTreeAll } from '@/api/system/auth/permission'
import { setAuth } from '@/api/system/auth/role'
const popupRef = ref<InstanceType<typeof Popup>>()

const emits = defineEmits<{
    (e: 'success'): void
}>()
interface FormData {
    id: string
    role: number[]
}

const checkedKeys = ref<number[]>([])
const halfCheckedKeys = ref<number[]>([])
const expandedKeys = ref<number[]>([])
const formData = reactive<FormData>({
    id: '',
    role: [],
})

const open = () => {
    popupRef.value?.open()
    getMenuTreeData()
}

interface MenuTreeItem {
    id: number
    name: string
    children: MenuTreeItem[]
}
const MenuTree = ref<MenuTreeItem[]>([])

// 获取所有节点ID
const getAllNodeIds = (nodes: MenuTreeItem[]): number[] => {
    const ids: number[] = []
    nodes.forEach(node => {
        ids.push(node.id)
        if (node.children?.length) {
            ids.push(...getAllNodeIds(node.children))
        }
    })
    return ids
}

const getMenuTreeData = async () => {
    const res = await getTreeAll()
    MenuTree.value = filterMenuTree(res)
    // 设置所有节点展开
    expandedKeys.value = getAllNodeIds(MenuTree.value)
    // 处理初始选中状态
    initCheckedStatus(formData.role)
}

// 过滤函数，只保留 id 和 name 字段
const filterMenuTree = (tree: MenuTreeItem[]): MenuTreeItem[] => {
    return tree.map(item => {
        const filteredItem: MenuTreeItem = {
            id: item.id,
            name: item.name,
            children: []
        };
        if (item.children && item.children.length > 0) {
            filteredItem.children = filterMenuTree(item.children);
        }
        return filteredItem;
    });
}

// 初始化选中状态
const initCheckedStatus = (roleIds: number[]) => {
    if (!roleIds?.length) return

    const checked = new Set<number>()
    const halfChecked = new Set<number>()

    // 递归处理节点
    const processNode = (node: MenuTreeItem) => {
        if (!node.children?.length) {
            // 叶子节点
            if (roleIds.includes(node.id)) {
                checked.add(node.id)
            }
            return roleIds.includes(node.id)
        }

        // 处理子节点
        const childrenResults = node.children.map(child => processNode(child))
        const allChildrenChecked = childrenResults.every(r => r)
        const someChildrenChecked = childrenResults.some(r => r)

        // 处理当前节点
        if (allChildrenChecked) {
            checked.add(node.id)
            return true
        } else if (someChildrenChecked || roleIds.includes(node.id)) {
            halfChecked.add(node.id)
            return false
        }
        return false
    }

    // 处理所有根节点
    MenuTree.value.forEach(node => processNode(node))

    checkedKeys.value = Array.from(checked)
    halfCheckedKeys.value = Array.from(halfChecked)
}

const handleSubmit = async () => {
    try {

        // 合并完全选中和半选节点，并按数字大小排序
        const allSelectedIds = [...new Set([...checkedKeys.value, ...halfCheckedKeys.value])]
            .sort((a, b) => a - b)

        formData.role = allSelectedIds
        // 这里可以继续处理提交逻辑
        await setAuth(formData)
        popupRef.value?.closeLoading()
        handleCancel();
        popupRef.value?.close()
        emits('success')
    } catch (error) {
        popupRef.value?.closeLoading()

    }

}

const setFormData = (data: Record<string, any>) => {
    console.log(data)
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const handleCancel = () => {
    checkedKeys.value = []
    halfCheckedKeys.value = []
    expandedKeys.value = []
    formData.role = []
    popupRef.value?.close()
}

defineExpose({
    open,
    setFormData
})
</script>
